<template>
<div
  class="letters"
  @touchstart.prevent="handleStart"
  @touchmove="handleMove"
  @touchend="handleEnd"
>
  <div
    class="letter"
    v-for="item of letters"
    :key="item"
    :ref="item"
    @click="handleClick"
  >{{item}}</div>
</div>
</template>

<script>
export default {
  name: 'Alphabet',
  data () {
    return {
      isTouch: false,
      timer: ''
    }
  },
  props: {
    all: Object
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.all) {
        letters.push(i)
      }
      return letters
    },
    startY () {
      return this.$refs['A'][0].offsetTop + 88
    }
  },
  methods: {
    handleClick (e) {
      this.$emit('onClick', e.target.innerText)
    },
    handleStart () {
      this.isTouch = true
    },
    handleEnd () {
      this.isTouch = false
    },
    handleMove (e) {
      if (this.isTouch) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const idx = Math.floor((e.touches[0].clientY - this.startY) / 18)
          if (idx >= 0 && idx < this.letters.length) {
            this.$emit('idxChange', this.letters[idx])
          }
        }, 16)
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
@import "~@style/variables.styl"
.letters
  position absolute
  top $header*2
  right 0px
  bottom 0px
  display flex
  flex-direction column
  justify-content center
  padding 0 6px
  text-align center
  .letter
    padding 2px 0
    color $bgcolor
</style>
